<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/26
 * Time: 11:38
 */
namespace app\index\controller;

use think\Db;
use think\Request;

class Onlineorder extends  Common{
	
	//判断是否登录
	public function _initialize()
	{
		parent::_initialize();
	}
	/**
	 * 线上结算主页
	 * @param string get.id 店铺id
	 * @return string id 店铺id
	*/
	public function index()
	{
		$id = input('get.sid');
		return view('index',compact('id'));
	}
	/**
	 * 查询商品
	 * @param string post.barcode 条形码
	 * @return json 查询结果
	*/
	public function barcode()
	{
		if(Request()->isAjax()){
			$barcode = input('post.barcode');
			$result = Db::table('product')->where('barcode',$barcode)->where('status',7)->find();
			return json($result);
		}
	}
	/**
	 * 结算
	 * @param string post.sid 店铺id
	 * @param string post.total 商品购买信息;
	 * @return json success 结算成功 error 结算失败错误信息
	*/
	public function settlement()
	{
		if(Request()->isAjax()){
			try{
				Db::startTrans();
				$total = json_decode(input('post.and'));
				$sid = input('post.sid');
				$input['postage'] = input('post.postage');
				$input['onlineorder'] = input('post.onlineorder');
				$input['ordernumber'] = time();
				$input['date'] = time();
				for($i=0;$i<count($total);$i++){
					//产品id
					$input['pid'] = $total[$i][0];
					//单价
					$input['retailprice'] = $total[$i][1];
					//销售数量
					$input['number'] = $total[$i][2];
					//条形码
					$input['barcode'] = $total[$i][3];
					//商品名称
					$input['pname'] = $total[$i][4];
					//总计
					$input['total'] = $total[$i][5];
					//商品图片
					$input['image'] = $total[$i][6];
					//店铺id
					$input['sid'] = $sid;
					$info = Db::table('inventory')->where('sid',$input['sid'])->where('pid',$input['pid'])->find();
					//增加卖出数
					$info['sellnumber'] = $info['sellnumber'] + $input['number'];
					$number = $info['number'] - $info['sellnumber'];
					if($number < 0){
						throw new \PDOException($total[$i][4].'库存不足');
					}
					$res = Db::table('inventory')->where('sid',$input['sid'])->where('pid',$input['pid'])->update(['sellnumber'=>$info['sellnumber']]);
					if(!$res){
						throw new \PDOException('库存修改失败');
					}
					$result[] = Db::table('online')->insertGetId($input);
				
					if(count($result) == 0){
						throw new \PDOException('订单添加失败');
					}
				}
				$value = Db::table('address')->where('sid',$sid)->find();
				$info = Db::table('online')->whereIn('id',$result)->select();
				$orderInfo = $this->typesetting($info,14,7,3,$value['address']);
				$resultMsg = json_decode(order_print($orderInfo,1,$value['printid']));
				if($resultMsg -> ret != 0){
					throw new \PDOException($resultMsg->msg);
				}
				Db::commit();
				$success = ['success'=>'结算成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	/**
	 * 线上购买记录
	 * @param string get.sid 店铺id
	 * @param string get.ordernumber 订单号
	*/
	public function onlinepurchase()
	{
		$where = ['query'=>[]];
		$sid = input('get.sid');
		$db = Db::table('online')->where('sid',input('get.sid'))
			->where('status','<>',2)->group('ordernumber');
		if(!empty(trim(input('get.ordernumber')))){
			$ordernumber = trim(input('get.ordernumber'));
			$db->where('ordernumber',$ordernumber);
			$where['query']['ordernumber'] = $ordernumber;
		}
		if(!empty(input('get.start')) && !empty(input('get.end'))){
			$start = input('get.start');
			$end = input('get.end');
			$db->whereTime('date','between', ["{$start}", "{$end}"]);
			$where['query']['start'] = $start;
			$where['query']['end'] = $end;
			$count = Db::table('online')->whereTime('date','between', ["{$start}", "{$end}"])->where('sid',$sid)->where('status',1)->sum('total');
		}else{
			$date = date("Y-m-d",time());
			$data = explode('-',$date);
			$ret = getStartAndEndUnixTimestamp($data[0],$data[1],$data[2]);
			$db->whereTime('date','between', ["{$ret['start']}","{$ret['end']}"]);
			$where['query']['start'] = $ret['start'];
			$where['query']['end'] = $ret['end'];
			$count = Db::table('online')->whereTime('date','between',["{$ret['start']}","{$ret['end']}"])->where('sid',$sid)->where('status',1)->sum('total');
		}
		$sid = input('get.sid');
		$where['query']['sid'] = input('get.sid');
		$result = $db->paginate(8,false,$where);
		return view('onlinepurchase',compact('sid','result','count','date','ordernumber','start','end'));
	}
	
	/**
	 * 详情
	 * @param string get.ordernumber 订单号
	*/
	public function detail(){
		$ordernumber = input('get.ordernumber');
		$sid = input('get.sid');
		$result = Db::table('online')
			->field('product.purchaseprice,online.onlineorder,online.pname,online.retailprice,online.number,
					online.ordernumber,online.date,online.total,online.postage,online.id')
			->join('product','product.id = online.pid','LEFT')
			->where('online.ordernumber',$ordernumber)
			->where('online.status','<>',2)->paginate(10);
		return view('detail',compact('result','sid'));
	}
	/**
	 * 删除订单
	 * @param string post.id 订单id
	 * @return json success 删除成功 error 删除失败
	*/
	public function delete()
	{
		if(request()->isAjax()){
			try{
				$id = input('post.id');
				$result = Db::table('online')->where('id',$id)->update(['status'=>2]);
				if(!$result){
					throw new \PDOException('删除失败');
				}
				$success = ['success'=>'删除成功'];
				return json($success);
			}catch (\PDOException $e){
				$error = ['error'=>'删除失败'];
				return json($error);
			}
		}
	}
	
	/**
	 * 飞鹅云排版
	 * @param $arr 要排版的数据
	 * @param $A 名称14
	 * @param $B 单价7
	 * @param $C 数量3
	 */
	function typesetting($arr,$A,$B,$C,$address)
	{
		$nums = 0;
		$orderInfo = '<CB>新品有戏</CB><BR>';
		$orderInfo .= '名称           单价   数量<BR>';//名称14 单价7 数量3 金额6-->这里的字节数可按自己需求自由改写
		$orderInfo .= '--------------------------------<BR>';
		foreach ($arr as $k5 => $v5) {
			$name = $v5['pname'];
			$price = $v5['retailprice'];
			$num = $v5['number'];
			//$prices = $v5['classid'];
			$kw3 = '';
			$kw1 = '';
			$kw2 = '';
			$kw4 = '';
			$str = $name;
			$blankNum = $A;//名称控制为14个字节
			$lan = mb_strlen($str,'utf-8');
			$m = 0;
			$j=1;
			$blankNum++;
			$result = array();
			for ($i=0;$i<$lan;$i++){
				$new = mb_substr($str,$m,$j,'utf-8');
				$j++;
				if(mb_strwidth($new,'utf-8')<$blankNum) {
					if($m+$j>$lan) {
						$m = $m+$j;
						$tail = $new;
						$lenght = iconv("UTF-8", "GBK//IGNORE", $new);
						$k = $A - strlen($lenght);
						for($q=0;$q<$k;$q++){
							$kw3 .= ' ';
						}
						$tail .= $kw3;
						break;
					}else{
						$next_new = mb_substr($str,$m,$j,'utf-8');
						if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
						else{
							$m = $i+1;
							$result[] = $new.'<BR>';
							$j=1;
						}
					}
				}
			}
			$head = '';
			foreach ($result as $value) {
				$head .= $value;
			}
			if(strlen($price) < $B){
				$k1 = $B - strlen($price);
				for($q=0;$q<$k1;$q++){
					$kw1 .= ' ';
				}
				$price = $price.$kw1;
			}
			if(strlen($num) < $C){
				$k2 = $C - strlen($num);
				for($q=0;$q<$k2;$q++){
					$kw2 .= ' ';
				}
				$num = $num.$kw2;
			}
//			if(strlen($prices) < $D){
//				$k3 = $D - strlen($prices);
//				for($q=0;$q<$k3;$q++){
//					$kw4 .= ' ';
//				}
//				$prices = $prices.$kw4;
//			}
			$orderInfo .= $head.$tail.' '.$price.' '.$num.'<BR>';
			@$nums += $price * $num;
		}
		$time = date('Y-m-d H:i:s',time());
		$orderInfo .= '--------------------------------<BR>';
		$orderInfo .= '合计：'.$nums.'元<BR>';
		$orderInfo .= '卖出地址：'.$address.'<BR>';
		$orderInfo .= '购买时间：'.$time.'<BR>';
		$orderInfo .= '<QR>http://admin.feieyun.com/index.php</QR>';
		return $orderInfo;
	}
	
}